import numpy as np
import cv2

def draw_circle(img, center, radius, color, thickness):
    cv2.circle(img, center, radius, color, thickness)

def find_circle_center(img, num_points=9):
    h, w = img.shape[:2]
    points = []

    for i in range(num_points):
        x = int(w * (i % 3) / 2)
        y = int(h * (i // 3) / 2)
        points.append((x, y))

    circle_centers = []
    for point in points:
        x, y = point
        roi = img[y-20:y+20, x-20:x+20]
        gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        circles = cv2.HoughCircles(gray_roi, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)

        if circles is not None:
            circles = np.uint16(np.around(circles))
            for circle in circles[0, :]:
                center_x = x + circle[0]
                center_y = y + circle[1]
                circle_centers.append((center_x, center_y))
                draw_circle(img, (center_x, center_y), circle[2], (0, 255, 0), 2)

    return img, circle_centers

def main():
    img = cv2.imread("calibration_board.jpg")
    img_with_circles, circle_centers = find_circle_center(img)

    cv2.imshow("Image with Circles", img_with_circles)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    print("Circle Centers:", circle_centers)

if __name__ == "__main__":
    main()


# import sys
# import cv2
# import numpy as np
# from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QFileDialog
# from PyQt5.QtGui import QImage, QPixmap
# from PyQt5.QtCore import Qt

# class CalibrationWidget(QWidget):
#     def __init__(self):
#         super().__init__()

#         self.image_label = QLabel()
#         self.image_label.setAlignment(Qt.AlignCenter)
#         self.open_image_button = QPushButton("打开图像")
#         self.start_calibration_button = QPushButton("开始标定")
#         self.end_calibration_button = QPushButton("结束标定")
#         self.result_label = QLabel()

#         self.open_image_button.clicked.connect(self.open_image)
#         self.start_calibration_button.clicked.connect(self.start_calibration)
#         self.end_calibration_button.clicked.connect(self.end_calibration)

#         layout = QVBoxLayout()
#         layout.addWidget(self.image_label)
#         layout.addWidget(self.open_image_button)
#         layout.addWidget(self.start_calibration_button)
#         layout.addWidget(self.end_calibration_button)
#         layout.addWidget(self.result_label)

#         self.setLayout(layout)

#         self.image = None
#         self.calibration_points = []

#     def open_image(self):
#         file_name, _ = QFileDialog.getOpenFileName(self, "打开图像", "", "图像文件 (*.jpg *.png)")
#         if file_name:
#             self.image = cv2.imread(file_name)
#             self.display_image(self.image)

#     def display_image(self, image):
#         height, width, _ = image.shape
#         bytes_per_line = 3 * width
#         qimage = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
#         self.image_label.setPixmap(QPixmap.fromImage(qimage))

#     def start_calibration(self):
#         if self.image is None:
#             return

#         self.calibration_points = []
#         self.image_label.mousePressEvent = self.mouse_press_event

#     def end_calibration(self):
#         if self.image is None or not self.calibration_points:
#             return

#         self.image_label.mousePressEvent = None
#         object_points = np.zeros((9, 3), np.float32)
#         object_points[:, :2] = np.mgrid[0:3, 0:3].T.reshape(-1, 2)

#         ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera([object_points], [np.array(self.calibration_points)], self.image.shape[::-1], None, None)
#         self.result_label.setText(f"标定结果：\nret = {ret}\nmtx = {mtx}\ndist = {dist}")

#     def mouse_press_event(self, event):
#         if len(self.calibration_points) < 9:
#             x, y = event.x(), event.y()
#             self.calibration_points.append((x, y))
#             cv2.circle(self.image, (x, y), 3, (0, 255, 0), -1)
#             self.display_image(self.image)

# app = QApplication(sys.argv)
# window = CalibrationWidget()
# window.show()
# sys.exit(app.exec_())